import axios from 'axios'
import {
	createUniAppAxiosAdapter
} from '@uni-helper/axios-adapter'
import {
	httpLogError,
	requestError,
	throttleToLogin
} from './utils.js'

export function createService() {
	// 创建一个axios实例，并且添加适配器
	const request = axios.create({
		adapter: createUniAppAxiosAdapter()
	})
	request.interceptors.request.use(
		(request) => {
			// console.log("request拦截器",request)
			return request
		},
		(err) => {
			return Promise.reject(err)
		}
	)
	request.interceptors.response.use(
		(response) => {
			// console.log("response拦截器", response)
			const dataAxios = response.data
			// 获取状态码 和 数据
			const {
				code,
				data
			} = dataAxios;
			// 判断code
			if (code === undefined) {
				return dataAxios
			} else {
				// 根据情况判断
				switch (`${code}`) {
					// 200没有错误
					case '200':
					case '00000':
						return data;
						// 请求出错
					case '400':
						return requestError(response);
					case '401':
						// 错误登录
						return throttleToLogin();
					default:
						// 不是正确的code
						return requestError(response);
				}
			}
		},
		(error) => {
			console.log(error)
			const status = error.response?.status
			switch (status) {
				case undefined:
				case null:
					httpLogError(error, "网路错误或跨域");
					break;
				case 400:
					httpLogError(error, "请求错误")
					break;
				case 401:
					httpLogError(error, '未授权，请登录')
					break
				case 403:
					httpLogError(error, '拒绝访问')
					break
				case 404:
					httpLogError(error, `请求地址出错: ${error.response.config.url}`)
					break
				case 408:
					httpLogError(error, '请求超时')
					break
				case 500:
					httpLogError(error, '服务器内部错误')
					break
				case 501:
					httpLogError(error, '服务未实现')
					break
				case 502:
					httpLogError(error, '网关错误')
					break
				case 503:
					httpLogError(error, '服务不可用')
					break
				case 504:
					httpLogError(error, '网关超时')
					break
				case 505:
					httpLogError(error, 'HTTP版本不受支持')
					break
				default:
					httpLogError(error, '请求错误')
					break
			}
		}
	)

	return request;
}

export const service = createService()